package com.ukefu.webim.util.weixin.handler;

import java.util.Map;

import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.client.UserClient;
import com.ukefu.webim.service.cache.CacheHelper;
import com.ukefu.webim.service.repository.WeiXinUserRepository;
import com.ukefu.webim.service.repository.WxMpEventRepository;
import com.ukefu.webim.web.model.WeiXinUser;
import com.ukefu.webim.web.model.WxMpEvent;

/**
 * @author Binary Wang
 */
@Component
public class UnsubscribeHandler extends AbstractHandler {

	@Autowired
	private WxMpEventRepository wxMpEventRes ;
	
	@Autowired
	private WeiXinUserRepository weiXinUserRes ;
	
    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
            Map<String, Object> context, WxMpService wxMpService,
            WxSessionManager sessionManager) {

    	String key = wxMessage.getFromUser();
		if (context != null && StringUtils.isNotBlank((String)context.get("snsid"))) {
			key = key + "_" + context.get("snsid");
		}
		WeiXinUser user = (WeiXinUser) UserClient.getUserClientMap().get(key);
    	if(user!=null){
    		WxMpEvent event = new WxMpEvent() ;
    		event.setFromuser(user.getOpenid());
    		event.setAppid(user.getSnsid());
    		event.setSnsid(user.getSnsid());
    		event.setChannel(UKDataContext.ChannelTypeEnum.WEIXIN.toString());
    		event.setCountry(user.getCountry());
    		event.setProvince(user.getProvince());
    		event.setCity(user.getCity());
    		event.setCreater(user.getOpenid());
    		event.setOrgi(user.getOrgi());
    		event.setUsername(user.getNickname());
    		event.setEvent(UKDataContext.EventTypeEnum.UNSUB.toString());
    		wxMpEventRes.save(event) ;
    		
    		user.setSubscribe(false);
    		weiXinUserRes.save(user) ;
    		
    		if(CacheHelper.getAiUserCacheBean().getCacheObject(user.getOpenid() , user.getOrgi()) != null) {
    			CacheHelper.getAiUserCacheBean().delete(user.getOpenid() , user.getOrgi());
    		}
    	}
        
        return null;
    }

}
